﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AppLab;
using AppLab.Data.Models;
using AppLab.Models;
using AppLab.Web;
using AppLab.Web.Services;
using Wicresoft.AppFlow.Flows;

namespace AppLab.Views
{
    public partial class Role : Page
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        private FlowContext flow = new FlowContext();
        private RolesForUser dtContext = new RolesForUser();

        public Role()
        {
            InitializeComponent();
            PageScrollViewer.SetIsMouseWheelScrollingEnabled(true);
            this.Title = ApplicationStrings.RolePageTitle;
            this.DataContext = dtContext;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            BindDataGrid();
        }

        #region DataGrid：加载
        private void BindDataGrid()
        {
            busyIndicatorLoad.IsBusy = true;
            var query = flow.GetRolesForUserQuery();
            var loadOp = flow.Load(query);
            loadOp.Completed += new EventHandler(loadOp_Completed);
        }

        void loadOp_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            dgRoleManagement.ItemsSource = loadOp.Entities;
            busyIndicatorLoad.IsBusy = false;
        }
        #endregion

        #region 角色改变
        //roleInt：选择的用户角色信息
        private RoleInt roleInt = new RoleInt();
        private void dgRoleManagement_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            roleInt = new RoleInt();
            RolesForUser role = this.dgRoleManagement.SelectedItem as RolesForUser;
            if (role != null)
            {
                roleInt.IsTerminalInfo = role.IsTerminalInfo;
                roleInt.IsSubmit = role.IsSubmit;
                roleInt.IsReview = role.IsReview;
                roleInt.IsTask = role.IsTask;
                roleInt.IsPublish = role.IsPublish;
                roleInt.IsRole = role.IsRole;
            }
        }

        private void ckBoxSubmit_Click(object sender, RoutedEventArgs e)
        {
            roleInt.IsSubmit = (bool)((CheckBox)sender).IsChecked ? 1 : 0;
        }

        private void ckBoxTerminalInfo_Click(object sender, RoutedEventArgs e)
        {
            roleInt.IsTerminalInfo = (bool)((CheckBox)sender).IsChecked ? 1 : 0;
        }

        private void ckBoxReview_Click(object sender, RoutedEventArgs e)
        {
            roleInt.IsReview = (bool)((CheckBox)sender).IsChecked ? 1 : 0;
        }

        private void ckBoxIsTask_Click(object sender, RoutedEventArgs e)
        {
            roleInt.IsTask = (bool)((CheckBox)sender).IsChecked ? 1 : 0;
        }

        private void ckBoxPublic_Click(object sender, RoutedEventArgs e)
        {
            roleInt.IsPublish = (bool)((CheckBox)sender).IsChecked ? 1 : 0;
        }

        private void ckBoxRole_Click(object sender, RoutedEventArgs e)
        {
            roleInt.IsRole = (bool)((CheckBox)sender).IsChecked ? 1 : 0;
        }
        #endregion

        private void SaveRolesForUser_Click(object sender, RoutedEventArgs e)
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                MessageBox.Show(PopupDialogStrings.MustBeLoggedInString, this.Title, MessageBoxButton.OK);
                return;
            }

            RolesForUser current = new RolesForUser();
            RolesForUser original = this.dgRoleManagement.SelectedItem as RolesForUser;

            current.Alias = original.Alias;
            current.DisplayName = original.DisplayName;
            current.IsTerminalInfo = roleInt.IsTerminalInfo;
            current.IsSubmit = roleInt.IsSubmit;
            current.IsReview = roleInt.IsReview;
            current.IsTask = roleInt.IsTask;
            current.IsPublish = roleInt.IsPublish;
            current.IsRole = roleInt.IsRole;

            dtContext.CurrentOperation = this.flow.RoleManagement(original, current, this.SaveRolesForUserOperation_Completed, null);
            this.possiblyPendingOperations.Add(dtContext.CurrentOperation);
        }

        private void ResetPassword_Click(object sender, RoutedEventArgs e)
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                MessageBox.Show(PopupDialogStrings.MustBeLoggedInString, this.Title, MessageBoxButton.OK);
                return;
            }

            if(MessageBoxResult.OK !=MessageBox.Show("确认要重置密码",this.Title,MessageBoxButton.OKCancel))
            {
                return;
            }

            if (this.dgRoleManagement.SelectedItem != null)
            {
                dtContext.CurrentOperation = this.flow.ResetPassword(this.dgRoleManagement.SelectedItem as RolesForUser, WebContext.Current.User.Name, this.PasswordChangedOperation_Completed, null);
                this.possiblyPendingOperations.Add(dtContext.CurrentOperation);
            }
        }

        private void DeleteUser_Click(object sender, RoutedEventArgs e)
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                MessageBox.Show("用户未登录！");
                return;
            }

            if (MessageBoxResult.OK != MessageBox.Show("确认要删除用户", this.Title, MessageBoxButton.OKCancel))
            {
                return;
            }

            if (this.dgRoleManagement.SelectedItem != null)
            {
                dtContext.CurrentOperation = this.flow.DeleteUser(this.dgRoleManagement.SelectedItem as RolesForUser, this.DeleteUserOperation_Completed, null);
                this.possiblyPendingOperations.Add(dtContext.CurrentOperation);
            }
        }

        private void SaveRolesForUserOperation_Completed(InvokeOperation<bool> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value)
                {
                    MessageBox.Show(PopupDialogStrings.SuccessedModifyRoleString);
                    this.NavigationService.Refresh();
                }
                else
                {
                    ErrorWindow.CreateNew(ErrorResources.ErrorWindowGenericError);
                }
            }
        }

        private void PasswordChangedOperation_Completed(InvokeOperation<bool> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value)
                {
                    MessageBox.Show("密码重置成功！");
                }
                else
                {
                    MessageBox.Show("密码重置失败！");
                }
            }
        }

        private void DeleteUserOperation_Completed(InvokeOperation<bool> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value)
                {
                    MessageBox.Show("删除用户成功！");
                    this.NavigationService.Refresh();
                }
                else
                {
                    MessageBox.Show("删除用户失败！");
                }
            }
        }

        private void RestoreRolesForUser_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Refresh();
        }
    }

    public class RoleInt
    {
        public int IsRegister { get; set; }
        public int IsTerminalInfo { get; set; }
        public int IsHistory { get; set; }
        public int IsSubmit { get; set; }
        public int IsReview { get; set; }
        public int IsTask { get; set; }
        public int IsPublish { get; set; }
        public int IsRole { get; set; }
    }
}
